package org.aphelie.chronicle.ui.forms;

import org.aphelie.chronicle.ArcElement;
import org.aphelie.chronicle.ui.editors.ArcFormEditor;
import org.aphelie.chronicle.ui.parts.IFormEntry;
import org.aphelie.chronicle.ui.parts.IFormEntryListener;
import org.aphelie.chronicle.ui.validators.TextValidator;
import org.eclipse.emf.edit.domain.EditingDomain;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.ui.forms.IManagedForm;
import org.eclipse.ui.forms.widgets.FormToolkit;

public abstract class ArcFormEntry extends FormEntry {

	private ArcFormSection section;
	protected ArcElement element;
	
	protected TextValidator validator;
	private IFormEntryListener listener;
	
	public ArcFormEntry(Composite parent, FormToolkit toolkit, ArcFormSection section, ArcElement element) {
		super(parent, toolkit, element.getLabel(), null, false);
		this.section = section;
		this.element = element;
		initialize();
	}
	
	protected void initialize() {
		setEditable(true);
		
		// TODO CDO IProject is null currently
		validator = new TextValidator(getManagedForm(), getText(), null, true) {
			@Override
			protected boolean validateControl() {
				return validateEntry();
			}
		};
		listener = new FormEntryAdapter(getSection()) {
			@Override
			public void textValueChanged(IFormEntry text) {
				try {
					setAttributeValue(element, text.getValue());
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		};
		setFormEntryListener(listener);
	}
	
	protected abstract boolean validateEntry();
	
	protected abstract void setAttributeValue(ArcElement element, String value);

	protected ArcFormSection getSection() {
		return section;
	}
	
	protected ArcElement getElement() {
		return element;
	}
	
	protected TextValidator getValidator;
	
	protected ArcFormEditor getEditor() {
		return section.getEditor();
	}
	
	protected IManagedForm getManagedForm() {
		return getSection().getManagedForm();
	}
	
	protected EditingDomain getEditingDomain() {
		return getEditor().getEditingDomain();
	}
	
}
